package com.hkj.shop.base.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

public class BaseController{
	protected Log logger = LogFactory.getLog(getClass());

	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
	{
		binder.registerCustomEditor(java.sql.Time.class, new CustomDateEditor(new SimpleDateFormat("hh:mm:ss"), true));
		binder.registerCustomEditor(java.sql.Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
//		binder.registerCustomEditor(java.sql.Timestamp.class, new CustomDateEditor(new SimpleDateFormat("yyy-MM-dd HHmmssZ"), true));
		
	}

	public String json(Object obj)
	{
		String json = null;
		try
		{
			ObjectMapper mapper = new ObjectMapper();
			json = mapper.writeValueAsString(obj);
		}
		catch (Exception e)
		{
			logger.error("解析json出错", e);
		}
		return json;
	}
	
	/*public <T> String toJson(Page<T> lists){
		// 定义返回的数据类型：json，使用了json-lib
        JSONObject jsonObj = new JSONObject();
        // 根据jqGrid对JSON的数据格式要求给jsonObj赋值
        jsonObj.put("page", lists.getPageNo());                // 当前页
        jsonObj.put("total", lists.getTotalPages());        // 总页数
        jsonObj.put("records", lists.getTotalItems());        // 总记录数
        
	    JsonConfig jsonConfig = new JsonConfig();
	    jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
	    jsonConfig.setExcludes(new String[]{"hibernateLazyInitializer"});//处理json因为引用实体进入死循环的问题
		JSONArray  json = JSONArray.fromObject(lists.getResult(), jsonConfig);
		jsonObj.put("rows", json);
		return jsonObj.toString();
	}*/
	
	
	protected Object getSessionAttribute(HttpServletRequest request, String attribute){
		HttpSession session = request.getSession(true);
		return session.getAttribute(attribute);
	}

	/**
	 * 输出响应
	 * 
	 * @param str
	 * @throws IOException
	 */
	protected void write(String str, HttpServletResponse response)
			throws IOException {
		response.getWriter().write(str);
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	/**
	 * 设置一个Session属性对象
	 * 
	 * @param request
	 * @param sessionName
	 * @return
	 */
	protected void setSessionAttribute(HttpServletRequest request,
			String sessionKey, Object objSessionAttribute) {
		HttpSession session = request.getSession();
		if (session != null)
			session.setAttribute(sessionKey, objSessionAttribute);
	}

	/**
	 * 移除Session对象属性值
	 * 
	 * @param request
	 * @param sessionName
	 * @return
	 */
	protected void removeSessionAttribute(HttpServletRequest request,
			String sessionKey) {
		HttpSession session = request.getSession();
		if (session != null)
			session.removeAttribute(sessionKey);
	}
	
	public String getLoginErrorString(int code, String msg, int pid) {
		logger.info("登录返回错误：" + msg);
		StringBuilder resStr = new StringBuilder();
		resStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><res>");
		resStr.append("<hd>");
		resStr.append("<code>").append(code).append("</code>");
		resStr.append("<desc>").append(msg).append("</desc>");
		resStr.append("<pid>").append(pid).append("</pid>");
		resStr.append("</hd>");
		resStr.append("</res>");
		return resStr.toString();
	}
	
	/**
	 * 显示异常信息
	 * @param Exception
	 * @return 
	 */
	protected String showException(Exception e){
		
		StackTraceElement[] se = e.getStackTrace();
		
		String message = "后台处理异常：" + e.getMessage()
			+ "\n文件[:" + se[0].getFileName() 
			+ "]\n类名[:" + se[0].getClassName()
			+ "]\n方法名[:" + se[0].getMethodName()
			+ "]\n代码行数[:" + se[0].getLineNumber() + "]";
		
		Map<String, Object> exceptionMessage = new HashMap<String, Object>();
		exceptionMessage.put("success", true);
		exceptionMessage.put("excptionMsg", message);
		return json(exceptionMessage);
	}
	
}

